<template>
  <view class="create-container">
    <!-- 组织信息标题 -->
    <view class="section-title">
      <text class="title-text">组织信息</text>
    </view>

    <!-- 表单内容 -->
    <view class="form-section">
      <!-- 公司名称 -->
      <view class="base-form-item" :class="{ active: !formData.name && isSubmit }">
        <view class="base-label-box">
          <text class="label">公司名称</text>
          <text class="required">*</text>
          <text class="fail-label" v-if="!formData.name && isSubmit">请填写公司名称</text>
        </view>
		
        <input
		v-if="!isEdit"
          class="input" 
          type="text" 
          v-model="formData.name" 
          placeholder="请输入公司名称"
          placeholder-style="color: #B5B5B5"
		 @input="nameInputChange"
        />
		 <text class="input" v-else>{{formData.name}}</text>
      </view>

      <!-- 管理员 -->
      <view class="base-form-item" :class="{ active: !formData.director && isSubmit }">
        <view class="base-label-box">
          <text class="label">管理员</text>
          <text class="required">*</text>
          <text class="fail-label" v-if="!formData.director && isSubmit">请填写管理员</text>
        </view>
        <text class="phone-text">{{formData.director}}</text>
      </view>

      <!-- 手机号 -->
      <view class="base-form-item">
        <view class="base-label-box">
          <text class="label">手机号</text>
          <text class="required">*</text>
        </view>
        <text class="phone-text">{{formatPhone(formData.phone)}}</text>
      </view>

      <!-- 省市区 -->
      <view class="base-form-item" :class="{ active: !region.text && isSubmit }">
        <view class="base-label-box">
          <text class="label">省市区</text>
          <text class="required">*</text>
          <text class="fail-label" v-if="!region.text && isSubmit">请选择省市区</text>
        </view>
        <view class="picker-value" @click="openRegionPicker">
          <text :class="{ placeholder: !region.text }">{{ region.text || '请选择' }}</text>
          <text class="arrow">></text>
        </view>
      </view>

      <!-- 详细地址 -->
      <view class="base-form-item" :class="{ active: !formData.address && isSubmit }">
        <view class="base-label-box">
          <text class="label">详细地址</text>
          <text class="required">*</text>
          <text class="fail-label" v-if="!formData.address && isSubmit">请填写详细地址</text>
        </view>
        <input 
          class="input" 
          type="text" 
          v-model="formData.address" 
          placeholder="请输入详细地址"
          placeholder-style="color: #B5B5B5"
		  @input="addressInputChange"
        />
      </view>
    </view>

    <!-- 资质信息标题 -->
    <view class="section-title">
      <text class="title-text">资质信息</text>
    </view>

    <!-- 资质信息内容 -->
    <view class="form-section">
      <!-- 证书选择 -->
      <template v-for="(item, key) in certList" :key="key">
        <view class="cert-form-item">
          <view class="cert-label-box">
            <text class="label">{{ item.label }}</text>
          </view>
          <view class="cert-group">
            <view 
              class="cert-item" 
              :class="{ active: formData.orgInfo[key] === '1' }"
              @click="formData.orgInfo[key] = '1'"
            >有</view>
            <view 
              class="cert-item" 
              :class="{ active: formData.orgInfo[key] === '0' }"
              @click="formData.orgInfo[key] = '0'"
            >无</view>
          </view>
        </view>
      </template>
    </view>

    <!-- 证明材料标题 -->
    <view class="section-title">
      <text class="title-text">证明材料</text>
    </view>

    <!-- 证明材料上传区 -->
    <view class="form-section">
      <view class="upload-section">
        <text class="upload-title">请上传附件信息</text>
        <view class="upload-area">
          <view class="upload-preview" v-for="(img, index) in imageList" :key="index">
            <image :src="img" mode="aspectFill"></image>
            <view class="delete-btn" @click="deleteImage(index)">×</view>
          </view>
          <view class="upload-btn" @click="chooseImage" v-if="imageList.length < 9">
            <text class="plus">+</text>
            <text class="upload-text">上传附件</text>
          </view>
        </view>
        <text class="upload-tip">(支持格式：jpg、jpeg、png格式)</text>
      </view>
    </view>

    <!-- 提交按钮 -->
    <view class="button-section">
      <button class="gvr-yellow-button submitbutton" @click="handleSubmit">提交</button>
    </view>
	
	<region-picker 
	  ref="regionPicker"
	  :initial-region="region"
	  @confirm="onRegionConfirm"
	  @cancel="onRegionCancel"
	/>
	<!-- 引入toast组件 -->
	<custom-toast ref="toastRef" :position="toastPosition"/>
  </view>
</template>

<script setup>
import { ref, computed,onMounted} from 'vue'
import CustomToast from '@/components/custom-toast/custom-toast.vue'
import RegionPicker from '@/components/region-picker/region-picker.vue'
import { onShow } from '@dcloudio/uni-app'
import { userStore } from '@/utils/userStore.js'
import { RouterMethods,Router} from '../../utils/router'
import { USER_TYPES, orgApi, userApi,fileApi} from '@/service/api'
import { formatPhone } from '@/utils/format'

// 用户信息
const userInfo = ref({
	type:'',
	userInfo: {
		phone:'',
		real_name:''
	}
})
// 是否是编辑模式
const isEdit = ref(false)
onMounted(() => {
  console.log('选择组织 onMounted')
  initUserInfo()
	
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1]
  const { type, data } = currentPage.options
  // 判断是否是编辑模式
  if (type === 'edit' && data) {
      isEdit.value = true
      try {
        // 解析传递的数据
        const decodedData = JSON.parse(decodeURIComponent(data))
		
	  // 使用对象展开运算符一次性赋值
		formData.value = {
			...formData.value,  // 保留原有的默认值
			...decodedData
		}
		region.value.text = `${formData.value.province} ${formData.value.city} ${formData.value.country} `
        imageList.value = Object.values(formData.value.images)
		console.log('更新后的表单数据:', JSON.stringify(formData.value, null, 2))
      } catch (error) {
        console.error('解析数据失败:', error)
      }
    } else {
		initFormData()
	}
  
})

// 页面显示时检查状态
onShow(() => {
  // console.log("选择组织 onShow")
  // initUserInfo()
})
// 初始化用户信息
const initUserInfo = () => {
  const storedInfo = userStore.getUserInfo()
  if (storedInfo) {
    userInfo.value = storedInfo
  }
}
	
const isSubmit = ref(false)
// 表单数据
const formData = ref({
  name: '',
  location: {
	  lon: 116.123, //东经为正，西经为负
	  lat: 39.456, //北纬为正，南纬为负
  },
  province: "",
  city: "",
  country: "",
  address: "",   
  director: "",
  phone: "",
  orgInfo: {
	 main_cert_1:null,
	 main_cert_2:null,
	 main_cert_3:null,
	 main_cert_4:null
  },
  images: {
  
  }
})
const initFormData = () => {
   formData.value.phone = userInfo.value.userInfo.phone
   formData.value.director = userInfo.value.userInfo.real_name
}


//图片
const imageList = ref([])
// //url
// const imageUrlList = ref([])

// 修改选择图片方法
const chooseImage = async () => {
  const remainCount = 9 - imageList.value.length
  if (remainCount <= 0) {
    uni.showToast({ title: '最多上传9张图片', icon: 'none' })
    return
  }
  
  uni.showLoading({ title: '选择图片中...' })
  
  try {
    const res = await new Promise((resolve, reject) => {
      uni.chooseImage({
        count: remainCount,
        success: resolve,
        fail: reject
      })
    })
    console.log(res.tempFilePaths)
    // 循环上传每张图片
    for (const tempFilePath of res.tempFilePaths) {
        imageList.value.push(tempFilePath)
    }
    
    uni.hideLoading()
  } catch (err) {
    console.error('选择图片失败:', err)
    uni.showToast({ title: '选择图片失败', icon: 'none' })
  }
}

// 修改删除图片方法
const deleteImage = (index) => {
  // 同时删除临时预览
  imageList.value.splice(index, 1)
}

// 证书列表
const certList = {
  main_cert_1: {label: '防爆电气设备安装、维修服务资质证书'},
  main_cert_2: { label: 'CMA检测资质' },
  main_cert_3: { label: '管理体系认证证书' },
  main_cert_4: { label: '石油公司入围服务机构' }
}
const nameInputChange = (e) => {
  isSubmit.value = false 
  console.log(e)
}

const addressInputChange = (e) => {
  isSubmit.value = false 
  console.log(e)
}


const region = ref({
	text: '',
	code: ''
})
const regionPicker = ref(null)

// 打开地区选择器
const openRegionPicker = () => {
  regionPicker.value.open()
}

// 确认选择地区
const onRegionConfirm = (regionObj) => {
  console.log(JSON.stringify(regionObj))
  let regionList = regionObj.text.split(' ')
  if (regionList.length == 3) {
  	 console.log(regionList[0])
  	 console.log(regionList[1])
  	 console.log(regionList[2])
  	 formData.value.province = regionList[0]
  	 formData.value.city = regionList[1]
  	 formData.value.country = regionList[2]
  	 region.value = regionObj
  }
}

// 取消选择地区
const onRegionCancel = () => {
  console.log('取消选择')
}

//更新用户信息
const getUserInfo = async() => {
	try {
		const result = await userApi.getUserInfo()
		if (result.code == undefined) {
		  return result
		} else {
		  throw new Error(result.msg || '获取用户信息失败')
		}
			   
	} catch (error){
	   uni.showToast({
		 title: error.message || '获取用户信息失败',
		 icon: 'none'
	   })
	}
}



// 提交表单
const handleSubmit = async () => {
   isSubmit.value = true
   
  if (!formData.value.name) {
    uni.showToast({ title: '请输入公司名称', icon: 'none' })
    return
  }
  if (!region.value) {
    uni.showToast({ title: '请选择省市区', icon: 'none' })
    return
  }
  if (!formData.value.address) {
    uni.showToast({ title: '请输入详细地址', icon: 'none' })
    return
  }
  
  try {
    // 显示上传loading
    uni.showLoading({ title: '正在上传图片...' })
  
    // 如果有图片需要上传
    if (imageList.value.length > 0) {
	  const urlList = imageList.value.filter((item)=>{
		  return item.includes('http://tmp');
	  })
	  const otherList = imageList.value.filter((item)=>{
	  	 return !item.includes('http://tmp');
	  })
	  let uploadResult = []
	  if (urlList.length > 0) {
        // 调用批量上传接口
         uploadResult = await fileApi.uploadMultiple(urlList)
	   }
	 
      
      // 上传成功后，将返回的URL按规则存入 formData.images
		let allImages = [...otherList,...uploadResult]
		let uploadMap = allImages.reduce((acc, url, index) => {
		  // 使用 main_comp_ 前缀加序号作为key
		  acc[`main_comp_${ index + 1}`] = url
		  return acc
		}, {})
		formData.value.images = uploadMap;
    } else {
		formData.value.images = {}
	}
  
    // 隐藏上传loading
    uni.hideLoading()
    
    // 显示提交loading
    uni.showLoading({ title: '正在提交信息...' })
  
     console.log(formData.value)
    // 提交用户信息
    let result = await (isEdit.value ? 
	      orgApi.updateOrg(formData.value) : 
	      orgApi.createOrg(formData.value))
    if (result.code == undefined) {
      console.log(result)
	  let userResult = await getUserInfo()
	  showSuccessToast(`组织${isEdit.value ? '编辑' : '创建'}成功。`)
     userStore.saveUserInfo(userResult)
      setTimeout(() => {
		  if(isEdit.value) {
		  	Router.back()
		  } else {
			RouterMethods.toRepairerCreateShare(result.id,true)
		  }
      }, 1300)
    } else {
      throw new Error(result.msg || '提交信息失败')
    }
  } catch (err) {
    // 隐藏所有loading
    uni.hideLoading()
    
    uni.showToast({
      title: err.message || '提交信息失败',
      icon: 'none'
    })
  }
}




// toast组件引用
const toastRef = ref(null)

// 自定义toast位置
const toastPosition = {
  bottom: 142 +'rpx',
  left: '58rpx',
  right: '58rpx',
}
// 显示成功提示
const showSuccessToast = (title) => {
  toastRef.value.showToast({
    text: title,
    type: 'success',
    duration: 2000
  })
}

// 显示失败提示
const showErrorToast = () => {
  toastRef.value.showToast({
    text: '组织创建失败，请稍后重试或联系客服。',
    type: 'error',
    duration: 2000
  })
}

</script>

<style scoped>
.create-container {
  min-height: 100vh;
  background-color: #FFFFFF;
  padding: 0 56rpx;
  padding-bottom: calc(82rpx + env(safe-area-inset-bottom));
}

.section-title {
  margin-top: 56rpx;
  display: flex;
  align-items: center;
  margin-bottom: 8rpx;
}

.title-text {
  font-family: PingFangSC-Medium;
  font-size: 32rpx;
  color: #000000;
  letter-spacing: 0;
  font-weight: 500;
}

.form-section {
  background-color: #FFFFFF;
}

.base-form-item {
  display: flex;
  flex-direction: column;
  padding-top: 40rpx;
  border-bottom: 2rpx solid #001E32;
}

.base-form-item.active {
  border-bottom: 2rpx solid #BA0C2F;
}

.base-label-box {
  display: flex;
  align-items: center;
  margin-bottom: 26rpx;
}

.required {
  font-family: PingFangSC-Medium;
  font-size: 28rpx;
  color: #BA0C2F;
  letter-spacing: 0;
  font-weight: 500;
}

.label {
  font-family: PingFangSC-Medium;
  font-size: 28rpx;
  color: #000000;
  letter-spacing: 0;
  font-weight: 500;
}

.fail-label {
  font-family: PingFangSC-Medium;
  font-size: 24rpx;
  color: #BA0C2F;
  letter-spacing: 0;
  font-weight: 500;
  margin-left: 10rpx;
}

.input {
  font-family: PingFangSC-Medium;
  font-size: 28rpx;
  color: #001E32;
  letter-spacing: 0;
  font-weight: 500;
  margin-bottom: 8rpx
}

.phone-text {
  font-family: PingFangSC-Medium;
  font-size: 28rpx;
  color: #001E32;
  letter-spacing: 0;
  font-weight: 500;
  margin-bottom: 8rpx
}

.picker-value {
  font-family: PingFangSC-Medium;
  font-size: 28rpx;
  color: #001E32;
  letter-spacing: 0;
  font-weight: 500;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 13rpx;
}

.placeholder {
  color: #B5B5B5;
}

.arrow {
  color: #001E32;
  font-size: 28rpx;
}

/* 资质证书部分 */
.cert-form-item {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  padding-top: 28rpx;
}

.cert-label-box {
  display: flex;
  align-items: center;
  padding-left: 28rpx;
  width: 40%;
}

.cert-group {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 336rpx;
}

.cert-item {
  width: 156rpx;
  height: 64rpx;
  border-radius: 10rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #DEDEDE;
  font-family: PingFangSC-Medium;
  font-size: 32rpx;
  color: #000000;
  letter-spacing: 0;
  text-align: center;
  font-weight: 500;
}

.cert-item.active {
  background: #285789;
  color: #FFFFFF;
}

/* 上传部分 */
.upload-section {
  padding: 32rpx 0;
}

.upload-title {
  font-family: PingFangSC-Medium;
  font-size: 28rpx;
  color: #000000;
  letter-spacing: 0;
  font-weight: 500;
}

.upload-area {
  margin-top: 14rpx;
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 30rpx;
  padding: 5rpx;
  margin-bottom: 16rpx;
}

.upload-preview {
  width: 190rpx;
  height: 190rpx;
  position: relative;
  border-radius: 4rpx;
  overflow: hidden;
  border: 2rpx solid #001E32;
}

.upload-preview image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.delete-btn {
  position: absolute;
  top: 8rpx;
  right: 8rpx;
  width: 32rpx;
  height: 32rpx;
  background: rgba(0, 0, 0, 0.4);
  color: #FFFFFF;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24rpx;
}

.upload-btn {
  width: 190rpx;
  height: 190rpx;
  background: #FFFFFF;
  border: 2rpx solid #001E32;
  border-radius: 4rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 8rpx;
}

.plus {
  font-size: 70rpx;
  color: #001E32;
  line-height: 1;
}

.upload-text {
  font-family: PingFangSC-Regular;
  font-size: 24rpx;
  color: #B5B5B5;
  letter-spacing: 0;
  text-align: center;
  font-weight: 400;
}

.upload-tip {
  font-family: PingFangSC-Medium;
  font-size: 20rpx;
  color: #B5B5B5;
  letter-spacing: 0;
  font-weight: 500;
}

/* 提交按钮 */
.submit-btn-wrapper {
  padding: 20rpx 32rpx;
  background: #FFFFFF;
}

/* 选择器弹窗样式 */
.picker-content {
  background: #FFFFFF;
  border-radius: 20rpx 20rpx 0 0;
}

.picker-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 88rpx;
  padding: 0 30rpx;
  border-bottom: 2rpx solid #001E32;
}

.cancel-btn {
  font-family: PingFangSC-Medium;
  font-size: 28rpx;
  color: #001E32;
  letter-spacing: 0;
  font-weight: 500;
}

.picker-title {
  font-family: PingFangSC-Medium;
  font-size: 32rpx;
  color: #000000;
  letter-spacing: 0;
  font-weight: 500;
}

.confirm-btn {
  font-family: PingFangSC-Medium;
  font-size: 28rpx;
  color: #3678BF;
  letter-spacing: 0;
  font-weight: 500;
}

.picker-view {
  width: 100%;
  height: 480rpx;
  z-index: 999;
}

.picker-item {
  line-height: 88rpx;
  text-align: center;
  font-family: PingFangSC-Medium;
  font-size: 28rpx;
  color: #001E32;
  letter-spacing: 0;
  font-weight: 500;
}
.button-section {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  padding-bottom: env(safe-area-inset-bottom);
  background-color: #FFFFFF;
}
.submitbutton {
  border-radius: 0;
}
</style>